/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.srwl.mytx.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.res.ResourcesCompat;

import com.amap.api.location.AMapLocation;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.MyApplication;
import com.srwl.mytx.R;
import com.srwl.mytx.contrack.RegisterContrack;
import com.srwl.mytx.contrack.RegisterPresenterImpl;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.im.IMSClientBootstrap;
import com.srwl.mytx.map.GaodeLocationClient;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.utils.GlideEngine;
import com.srwl.mytx.utils.IMImageUtils;
import com.srwl.mytx.utils.ImageUtils;
import com.srwl.mytx.utils.PermissionsUtils;
import com.srwl.mytx.utils.StringUtil;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;
import com.starrtc.starrtcsdk.api.XHClient;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;


/**
 * register screen
 */
public class RegisterActivity extends BaseRegisterActivity<RegisterContrack.Presenter> implements RegisterContrack.View, PermissionsUtils.IPermissionsResult {
    private static final String TAG = "RegisterActivity";
    private static final int PERMISSION_REQUEST_CODE = 0;

    private EditText et_name;
    private EditText et_phone;
    private EditText et_password;
    private Button btn_register;

    private ImageView iv_hide;
    private ImageView iv_show;
    private CircleImageView cv_avatar;


    String avatarPath = "";
    Bitmap bitmap;
    Button btn_sendMobileCode;
    EditText et_mobileCode;
    EditText et_area;
    Context context;
    public TextView tv_findPassWord;
    GaodeLocationClient location;
    private ProgressDialog progressDialog;
    //   List<Uri> selectedPhotos;
    private String phone;
    private String defaultAvatar;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
//        Toolbar toolbar = findViewById(R.id.toolbar);
//        toolbar.setTitle("注册");
//        setSupportActionBar(toolbar);
        context = this;
        avatarPath = Helper.getInstance().getBasePath() + File.separator;
        File file = new File(avatarPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        avatarPath += getString(R.string.avatar_name);
        et_name = findViewById(R.id.et_name);
        et_phone = findViewById(R.id.et_phone);
        et_password = findViewById(R.id.et_password);
        btn_sendMobileCode = findViewById(R.id.btn_send_mobile_code);
        et_mobileCode = findViewById(R.id.et_mobile_code);
        et_area = findViewById(R.id.tv_area);
        tv_findPassWord = findViewById(R.id.tv_forget_pass_word);
        btn_register = findViewById(R.id.btn_register);
        cv_avatar = findViewById(R.id.avatar);
        iv_hide = findViewById(R.id.iv_hide);
        iv_show = findViewById(R.id.iv_show);

        initTextChangeListener();
        iv_hide.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                iv_hide.setVisibility(View.INVISIBLE);
                iv_show.setVisibility(View.VISIBLE);
                et_password
                        .setTransformationMethod(HideReturnsTransformationMethod
                                .getInstance());
                // 切换后将EditText光标置于末尾
                et_password.setSelection(et_password.getText().length());

            }

        });
        iv_show.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                iv_show.setVisibility(View.INVISIBLE);
                iv_hide.setVisibility(View.VISIBLE);
                et_password
                        .setTransformationMethod(PasswordTransformationMethod
                                .getInstance());
                // 切换后将EditText光标置于末尾
                et_password.setSelection(et_password.getText().length());
            }

        });

        User loginUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
        if (!TextUtils.isEmpty(loginUserInfo.getuId())) {//如果用户id 是不是空的，我们认为是临时用户进入了注册页面，把临时用户头像作为 用户的默认头像
            defaultAvatar = loginUserInfo.getAvatar();
        }

        cv_avatar.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //  checkPermissions();
                String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
                PermissionsUtils.getInstance().checkPermissions(RegisterActivity.this, permissions, RegisterActivity.this);
            }

        });

        btn_register.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                register();

            }

        });
        btn_sendMobileCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (et_phone.getCurrentTextColor() == Color.RED) {
                    et_phone.setTextColor(getResources().getColor(R.color.text_black));
                }
                String phone = et_phone.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    et_phone.setHint("手机号不能为空");
                    Utils.editViewValueErrorAnimate(et_phone, context);
                    et_phone.setPadding(Utils.dpToPx(90, context), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效
                    return;
                }

                if (!Utils.checkMobileNum(phone)) {
                    showToast(btn_sendMobileCode, getString(R.string.phone_number_type_error));
                    et_phone.setTextColor(Color.RED);
                    Utils.editViewValueErrorAnimate(et_phone, context);
                    et_phone.setPadding(Utils.dpToPx(90, context), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效
                    return;
                }
                et_mobileCode.setText("");
                presenter.sendMobileCode(phone);

            }
        });
        tv_findPassWord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(RegisterActivity.this, ReplacePassWordActivity.class));
            }
        });
        initProgressDialog();
        //清空缓存中的用户数据
        //  Helper.getInstance().removeLoginUserInfo();
        String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
        PermissionsUtils.getInstance().checkPermissions(RegisterActivity.this, permissions, new PermissionsUtils.IPermissionsResult() {
            @Override
            public void onGranted() {
                initLocation();
            }

            @Override
            public void onDenied(List<String> deniedPermissionList) {

            }
        });

        // IMSClientBootstrap.getInstance().init(getApplicationContext());
    }

    private void initTextChangeListener() {
        et_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (et_name.getCurrentTextColor() == Color.RED) {
                    et_name.setTextColor(getResources().getColor(R.color.text_black));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                String userName = StringUtil.checkUserName(s.toString());
//                if (isError) {
//                    et_name.setTextColor(Color.RED);
//                    showToast("姓名中含有特殊符号，请检查");
//                }

                if (!TextUtils.equals(userName, s.toString())) {
                    et_name.setText(userName);
                    Log.d(TAG, "afterTextChanged: " + userName);
                    if (!TextUtils.isEmpty(userName)) {
                        et_name.setSelection(userName.length());
                    }
                }
            }
        });

        et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (et_password.getCurrentTextColor() == Color.RED) {
                    et_password.setTextColor(getResources().getColor(R.color.text_black));
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (s.length() > 20) {
                    s.delete(20, 21);
                }
//                if (et_password.getText().length() >= 6) {
//                    //检测密码强度
//                    showToast(et_password, "密码强度：" + StringUtil.validatePassWord(et_password.getText().toString()));
//                }
            }
        });

        et_password.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    if (et_password.getText().length() > 0 && et_password.getText().length() < 6) {
                        showToast(et_password, "密码长度少于6位");
                        et_password.setTextColor(Color.RED);
                    }
                }
            }
        });

        et_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (et_phone.getCurrentTextColor() == Color.RED) {
                    et_phone.setTextColor(getResources().getColor(R.color.text_black));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        et_mobileCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (et_mobileCode.getCurrentTextColor() == Color.RED) {
                    et_mobileCode.setTextColor(getResources().getColor(R.color.text_black));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    RegisterContrack.Presenter initPresenter() {
        return new RegisterPresenterImpl(this, this);
    }

    private void initLocation() {
        location = new GaodeLocationClient(this, true);
        location.setLocationListener(new GaodeLocationClient.LocationListener() {
            @Override
            public void locationSuccess(final AMapLocation location) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        et_area.setText(location.getCountry() + location.getCity() + location.getDistrict());
                    }
                });
            }
        });

    }

    /**
     * 检测各输入项是否有值
     */
    public void register() {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_unavailable));
            return;
        }

        hideSoftKeyboard();
        String password = et_password.getText().toString().trim();
        String mobileCode = et_mobileCode.getText().toString().trim();
        phone = et_phone.getText().toString().trim();
        String name = et_name.getText().toString().trim();
        String address = et_area.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            Utils.editViewValueErrorAnimate(et_name, context);
            et_name.setPadding(Utils.dpToPx(90, context), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效

            return;
        }
        if (TextUtils.isEmpty(phone)) {
            et_phone.setHint("手机号不能为空");
            Utils.editViewValueErrorAnimate(et_phone, context);
            et_phone.setPadding(Utils.dpToPx(90, context), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效

            return;
        }
        if (!Utils.checkMobileNum(phone)) {
            showToast(btn_register, getString(R.string.phone_number_type_error));
            et_phone.setTextColor(Color.RED);
            Utils.editViewValueErrorAnimate(et_phone, context);
            et_phone.setPadding(Utils.dpToPx(90, context), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效
            return;
        }

        if (TextUtils.isEmpty(mobileCode)) {
            et_mobileCode.setHint("验证码不能为空");
            Utils.editViewValueErrorAnimate(et_mobileCode, context);
            et_mobileCode.setPadding(Utils.dpToPx(90, context), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效
            return;
        }

        if (TextUtils.isEmpty(password)) {
            et_password.setHint("密码不能为空");
            Utils.editViewValueErrorAnimate(et_password, context);
            et_password.setPadding(Utils.dpToPx(90, context), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效

            return;
        }

        if (password.length() < 6) {
            showToast(btn_register, "密码长度不足6位");
            Utils.editViewValueErrorAnimate(et_password, context);
            et_password.setPadding(Utils.dpToPx(90, context), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效

            return;
        }


        //判断是否设置头像，提示用户，
//        if (bitmap == null) {
//            Utils.viewValueEmptyAnimate(cv_avatar);
//            showToast(btn_register, "右上角设置头像");
//            return;
//        }

        User user = new User();
        user.setPhone(phone);
        user.setPassword(password);
        user.setUsername(name);
        user.setArea(address);
        user.setAvatar(defaultAvatar);
        presenter.register(user, mobileCode);
    }

    // 头像选择
    private void pickAvatar() {
//        Matisse.from(this)
//                .choose(MimeType.ofImage())
//                //.theme(R.style.Matisse_Dracula)
//                .countable(true)
//                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
//                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
//                .thumbnailScale(0.85f)
//                .imageEngine(new GlideEngine())
//
//                .forResult(EaseConstant.REQUEST_CODE_PICK_AVATAR);

        EasyPhotos.createAlbum(this, true, GlideEngine.getInstance())
                .setFileProviderAuthority("com.srbl.mytx.fileProvider")
                .setCount(1)
                .start(EaseConstant.REQUEST_CODE_PICK_AVATAR);
                /*.start(new SelectCallback() {
                           @Override
                           public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                               UCrop.Options options = new UCrop.Options();
                               options.setCircleDimmedLayer(true);
                               options.setToolbarColor(ResourcesCompat.getColor(getResources(), R.color.colorPrimary, null));
                               options.setStatusBarColor(ResourcesCompat.getColor(getResources(), R.color.colorPrimaryDark, null));
                               File file = new File(avatarPath);
                               if (!file.exists()) {
                                   file.mkdirs();
                               }
                               String avatarPath_v1 = avatarPath + getString(R.string.avatar_name);
                               UCrop.of(photos.get(0).uri, Uri.parse(avatarPath_v1))
                                       .withAspectRatio(1, 1)
                                       .withMaxResultSize(480, 480)
                                       .withOptions(options)
                                       .start(RegisterActivity.this, EaseConstant.REQUEST_CODE_CROP);

                           }
                       }
                );*/
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case EaseConstant.REQUEST_CODE_PICK_AVATAR:
                    ArrayList<Photo> photos = data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS);
                    if (photos==null||photos.size()==0){
                        Log.e(TAG, "onActivityResult: 返回的图片为0");
                        return;
                    }
                    UCrop.Options options = new UCrop.Options();
                    options.setCircleDimmedLayer(true);
                    options.setToolbarColor(ResourcesCompat.getColor(getResources(), R.color.colorPrimary, null));
                    options.setStatusBarColor(ResourcesCompat.getColor(getResources(), R.color.colorPrimaryDark, null));
                    Uri uri;
                    if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { //10.0系统以下，不能直接使用uri ，否则很多手机 无法裁剪图片
                        uri = Uri.fromFile(new File(photos.get(0).path));
                    } else {
                        uri = photos.get(0).uri;
                    }

                    UCrop.of(uri, Uri.parse(avatarPath))
                            .withAspectRatio(1, 1)
                            .withMaxResultSize(480, 480)
                            .withOptions(options)
                            .start(RegisterActivity.this, EaseConstant.REQUEST_CODE_CROP);
                    break;
                case EaseConstant.REQUEST_CODE_CROP:// 裁剪后回传
                    Uri resultUri = UCrop.getOutput(data);
                    bitmap = BitmapFactory.decodeFile(resultUri.getPath());
                    bitmap = IMImageUtils.toRoundBitmap(this.bitmap);
                    ImageUtils.save(bitmap, avatarPath, Bitmap.CompressFormat.PNG);

                    cv_avatar.setImageBitmap(bitmap);
            }
        } else if (resultCode == UCrop.RESULT_ERROR) {
            final Throwable cropError = UCrop.getError(data);
            cropError.printStackTrace();

        }
    }


    @Override
    protected void onResume() {

        super.onResume();
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
        PermissionsUtils.getInstance().clear();
    }

    @Override
    public void setPresenter(RegisterContrack.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void showRegisterSuccess() {
        disMissProgressDialog();
        //临时用户注册的情况
        if (IMSClientBootstrap.getInstance().isActive()) {//因为 startRTC 总是和我们自己的im 同步登录，所以可以用我们im 是否存活来判断 starRTC 是否登录，如果登录了的，需要先登出
            finish();//关闭当前注册页面
            MyApplication.getInstance().finishActivity(LoginActivity.class);//finish登录页面,这样临时用户注册后，就会回到来源页面
            XHClient.getInstance().getLoginManager().logout();//startRTC 登录过，需要先登出
            Helper.getInstance().onAccountChange();
        } else {// 正常用户退出登录后，进入注册页面注册的情况
            MyApplication.getInstance().finishActivities();//关闭全部页面
            //非零时用户直接跳转主页面
            Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
            startActivity(intent);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                IMSClientBootstrap.getInstance().login();
            }
        }).start();

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);//睡眠2s 是为了 避免startRTC 在调用登录后，立马调用初始化并登录，出问题，消息发不出去，，，
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Helper.getInstance().initStarRtc(UserProfileManager.getInstance().getLoginUserInfo().getuId());
                Helper.getInstance().starRtcLogin();
            }
        });
        thread.start();

        if (bitmap != null) {
            presenter.uploadAvatar();
        }
    }

    @Override
    public void showRegisterFail() {
        et_mobileCode.setTextColor(Color.RED);
    }

    @Override
    public void showSendMobileCodeSuccess() {

    }

    @Override
    public void setSendMobileCodeButtonText(final String count) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btn_sendMobileCode.setText(count);
            }
        });
    }

    @Override
    public void showSendMobileCodeFail() {
        et_phone.setTextColor(Color.RED);
    }

    @Override
    public void showToast(String message) {
        super.showToast(btn_register, message);
        // Toast.makeText(context, message, Toast.LENGTH_LONG).show();
        //Snackbar.make(container, message, Snackbar.LENGTH_INDEFINITE).show();
    }

    @Override
    public void showRetrievePassWord() {
        tv_findPassWord.setVisibility(View.VISIBLE);
    }

    @Override
    public void showProgressDialog(String message) {
        if (progressDialog == null) {
            initProgressDialog();
        }
        progressDialog.setMessage(message);
        progressDialog.show();
    }


    @Override
    public void disMissProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    @Override
    public void showValiueEmputy(int viewId) {

    }


    @Override
    public void setSendMobileCodeButtonStatus(final boolean bool) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btn_sendMobileCode.setEnabled(bool);
            }
        });
    }

    @Override
    public void setRegisterButtonStatus(boolean bool) {
        btn_register.setEnabled(bool);
    }

    public void initProgressDialog() {
        progressDialog = new ProgressDialog(context);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    }


    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionsUtils.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    @Override
    public void onGranted() {
        pickAvatar();
    }

    @Override
    public void onDenied(List<String> deniedPermissionList) {
        ConfirmDialog dialog = new ConfirmDialog(RegisterActivity.this, "提醒", "使用 [储存空间] 的权限被禁止，去设置？", "去设置", "取消", true);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                Uri packageURI = Uri.parse("package:" + getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                context.startActivity(intent);
            }
        });

        dialog.show();
    }
}

